<?php

namespace Modules\Admin\Http\Controllers\Users;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Modules\Common\General\Security\Api\Gateway;
use Modules\Common\Models\AdminLog;
use Modules\Common\Models\Users;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;
use Modules\Common\Models\ActivationCodeUsage;
use Modules\Common\Models\SubscriptionRecords;
use Modules\Common\Models\Members;

class Retrieve
{
    /**
     * 获取用户信息
     *
     * @Route(path="/api/admin/user")
     */
    public function retrieve()
    {
        $query = Users::with(['orders', 'members']);
        // 用户名称
        if (request('username')) {
            $query->where('nickname', 'like', '%' . request('username') . '%');
        }
        //用户id
        if (request('user_id')) {
            $query->where('id', '=',request('user_id'));
        }
        //手机号
        if (request('phone')) {
            $query->where('phone', 'like', '%' . request('phone') . '%');
        }

        // 会员注册时间
        $start_date =request('start_date');
        $end_date =request('end_date');
        if ($start_date&&$end_date){
            // 获取匹配的用户 ID 列表
           $userIds = DB::connection('mysql')->table('members')
                ->where('start_date', '>=', $start_date)
                ->where(function ($query) use ($end_date) {
                    $query->where('start_date', '<=', $end_date)
                          ->orWhere('end_date', '>=', '9999-12-31 00:00:00'); // 假设永久会员的结束日期是这个值
                })
                ->where('status', 1)
                ->pluck('user_id')
                ->all();
            // 确保获取到了用户 ID
            if (count($userIds) > 0) {
                $query->whereIn('id', $userIds);
            } else {
                // 如果没有匹配的用户，返回空结果
                $query->whereNull('id');
            }
        }
        $query->orderByRaw('id desc , created_at desc');

        $sidDefault = auth('api')->user()->sid;
        $eidDefault = auth('api')->user()->eid; 
        $users = $query->where('eid',$eidDefault)->paginate(request('per_page', 15));
        // 获取用户列表并附加会员订阅和消费总额信息
        $users->getCollection()->transform(function ($user) {
            // 初始化会员状态
            $user->is_member = false;
            $total_spent = 0;
        
            // 检查会员状态
            foreach ($user->members as $membership) {
                if ($membership->status == 1) {
                    $user->is_member = true;
                    break;
                }
            }
        
            // 计算支付成功的订单总额
            foreach ($user->orders as $order) {
                if ($order->status == 2 && is_null($order->deleted_at)) {
                    $total_spent += (float)$order->total_amount; // 确保金额是数值类型
                }
            }
            // 实体卡激活
            $activationCodeUsage_count = ActivationCodeUsage::where('user_id', $user->id)->count();
            // 批量激活
            $subscriptionRecords_count = SubscriptionRecords::where('user_id', $user->id)->count();
            // 购买订阅
            $members_count = Members::where('user_id', $user->id)->count();
            
            // 初始化订阅方法
            $subscription_method = "暂无订阅";
            
            // 根据条件设置订阅方法
            if ($activationCodeUsage_count > 0) {
                //激活订阅卡
                $subscription_method = "激活订阅卡";
            } elseif ($subscriptionRecords_count > 0) {
                //后台激活
                $subscription_method = "后台激活";
            } elseif ($members_count > 0) {
                //自行购买
                $subscription_method = "自行购买";
            }
            
            // 将订阅方法设置到用户对象
            $user->subscription_method = $subscription_method;
            $user->total_spent = $total_spent;
            return $user;
        });
        return Api::success($users);
    }
}